package common

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"errors"
	"github.com/valyala/fasthttp"
	"math/rand"
	"time"
)

type SendData struct {
	Status int          `json:"status"`
	Msg    string       `json:"msg"`
	Data   interface{} `json:"data"`
}

//
// response data
//
func SendMsg(ctx *fasthttp.RequestCtx, status int, content interface{}) {
	ctx.Response.Header.SetContentType("application/json")

	var sendData *SendData
	if status == 200 {
		sendData = &SendData{
			Status: status,
			Msg:    "成功",
			Data:   content,
		}
	} else {
		if GlobalConf.Debug == "false" {
			status = 500
		}

		sendData = &SendData{
			Status: status,
			Msg:    content.(string),
			Data:   "",
		}
	}
	jsonData, _ := json.Marshal(sendData)

	ctx.Write(jsonData)
}


/*
 *生成随机字符串
 * l        int  rand string length
 * s_type   int  rand string type [1=>A-Z+a-z+0-9 2=>A-Z 3=>a-z 4=>0-9  5=>A-Z+a-z 6=>A-Z+0-9 7=>a-z+0-9]
 */

func GetRandomStringByCondition(l int, s_type int) (string, error) {
	capitals := "ABCDEFGHIGKLMNOPQRSTUVWSYZ"
	lower := "abcdefghijklmnopqrstuvwxyz"
	number_s := "0123456789"

	var str string
	switch s_type {
	case 1:
		str = capitals + lower + number_s
	case 2:
		str = capitals
	case 3:
		str = lower
	case 4:
		str = number_s
	case 5:
		str = capitals + lower
	case 6:
		str = capitals + number_s
	case 7:
		str = lower + number_s
	default:
		return "", errors.New("Unknown parameter `s_type` ! ")
	}
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result), nil
}

/**
 * 将参数生成MD5字符串
 */
func GetMD5ByString(s string) string {
	md5Ctx := md5.New()
	md5Ctx.Write([]byte(s))
	cipherStr := md5Ctx.Sum(nil)
	return hex.EncodeToString(cipherStr)
}
